package com.ares.basic.config;

import com.ares.basic.contexthelp.ApplicationContextHelper;
import com.ares.basic.crypt.BCryptPasswordEncoder;
import com.ares.basic.http.PoolingHttpExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class BasicConfig {

    @Bean
    public ApplicationContextHelper applicationContextHelper() {
        return new ApplicationContextHelper();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean("poolingHttpExecutor")
    public PoolingHttpExecutor poolingHttpExecutor() {
        return new PoolingHttpExecutor();
    }

    @Bean(name = "commonThreadPool")
    public ThreadPoolTaskExecutor taskExecutor() {
        int i = Runtime.getRuntime().availableProcessors();
        i = i > 6 ? 6 : i;

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(i);
        // 设置最大线程数
        executor.setMaxPoolSize(i * 2);
        // 设置队列容量
        executor.setQueueCapacity(800);
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("common-");
        // 线程池对拒绝任务（无线程可用）的处理策略，目前只支持AbortPolicy、CallerRunsPolicy；默认为后者
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //调度器shutdown被调用时等待当前被调度的任务完成
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //执行初始化
        executor.initialize();
        return executor;
    }
}
